<template>
  <view class="code-wrap">
    <input class="code" type="number" :value="val" :focus="focus" @focus="focus = true" @blur="focus = false" :disabled="disabled" :maxlength="length" @input="handleInput" />
    <view
      class="labels pi-grid pi-col-space-16"
      :class="{ 'pi-col-2': length === 2, 'pi-col-3': length === 3, 'pi-col-4': length === 4, 'pi-col-5': length === 5, 'pi-col-6': length === 6 }"
    >
      <view :key="index" class="label" :class="{ active: focus === true && index === currentIndex }" v-for="(item, index) in length" @tap="focus = true">
        <view>{{ arrCode[index] || '' }}</view>
      </view>
    </view>
  </view>
</template>

<script>
import ValueMixin from '../mixin/value-mixin.js'

export default {
  name: 'DigitalInput',
  mixins: [ValueMixin],
  props: {
    // 长度
    length: {
      required: false,
      type: Number,
      default: 4
    },
    autoFocus: {
      required: false,
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      focus: false,
      disabled: false,
      data() {
        return {
          val: this.value
        }
      }
    }
  },
  mounted() {    
    if (this.autoFocus) {
      setTimeout(() => {
        this.focus = true
      }, 500)
    }
  },
  computed: {
    arrCode: function() {
      return this.val.split('')
    },
    currentIndex: function() {
      return this.val.length
    }
  },
  methods: {
    handleInput(e) {
      const value = e.detail.value
      const val = value.replace(/[^\d]/g, '') // 限制非数字
      this.$emit('change', this.val)
      if (value.length <= this.length) {
        this.val = val
      }
      if (value.length === this.length) {
        this.$emit('end', this.val)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@keyframes flicker {
  100% {
    opacity: 0;
  }
}

.code-wrap {
  .code {
    position: absolute;
    left: -5000rpx;
    width: 100%;
    height: 40px;
    font-size: 35px;
    overflow: hidden;
    border: none;
    outline: none;
    opacity: 0;
    -webkit-tap-highlight-color: transparent;
  }
  .labels {
    -webkit-tap-highlight-color: transparent; // 解决ios点击灰色阴影的问题
  }
  .label {
    position: relative;
    height: 98rpx;
    line-height: 98rpx;
    border-bottom: 2rpx solid #eeeeee;
    color: #313131;
    font-size: 48rpx;
    font-weight: 500;
    text-align: center;
    &.active:after {
      // 伪类实现光标效果
      content: ' ';
      position: absolute;
      top: 50%;
      height: 50%;
      transform: translateY(-50%);
      width: 4rpx;
      background: #666666;
      animation: 1s flicker infinite;
    }
  }
}
</style>
